package com.example.ssrbac.controller;

import com.example.ssrbac.dto.RoleDTO;
import com.example.ssrbac.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Set;

/**
 * 角色控制器
 * 
 * 该控制器负责处理角色管理相关的请求，包括：
 * 1. 创建角色
 * 2. 更新角色信息
 * 3. 删除角色
 * 4. 查询角色信息
 * 5. 为角色分配权限
 * 
 * @author Your Name
 * @version 1.0
 */
@RestController
@RequestMapping("/api/roles")
public class RoleController {
    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

    /**
     * 角色服务，用于处理角色相关的业务逻辑
     */
    @Autowired
    private RoleService roleService;

    /**
     * 创建新角色
     * 需要ROLE_CREATE权限
     * 
     * @param roleDTO 角色信息
     * @return 创建的角色信息
     */
    @PostMapping
    @PreAuthorize("hasAuthority('ROLE_CREATE')")
    public ResponseEntity<RoleDTO> createRole(@Valid @RequestBody RoleDTO roleDTO) {
        logger.info("Creating new role with name: {}", roleDTO.getName());
        RoleDTO createdRole = roleService.createRole(roleDTO);
        logger.info("Role created successfully with ID: {}", createdRole.getId());
        return ResponseEntity.ok(createdRole);
    }

    /**
     * 更新角色信息
     * 需要ROLE_UPDATE权限
     * 
     * @param id 角色ID
     * @param roleDTO 更新的角色信息
     * @return 更新后的角色信息
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_UPDATE')")
    public ResponseEntity<RoleDTO> updateRole(@PathVariable Long id, @Valid @RequestBody RoleDTO roleDTO) {
        logger.info("Updating role with ID: {}", id);
        RoleDTO updatedRole = roleService.updateRole(id, roleDTO);
        logger.info("Role updated successfully: {}", id);
        return ResponseEntity.ok(updatedRole);
    }

    /**
     * 删除角色
     * 需要ROLE_DELETE权限
     * 
     * @param id 角色ID
     * @return 空响应
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_DELETE')")
    public ResponseEntity<Void> deleteRole(@PathVariable Long id) {
        logger.info("Deleting role with ID: {}", id);
        roleService.deleteRole(id);
        logger.info("Role deleted successfully: {}", id);
        return ResponseEntity.ok().build();
    }

    /**
     * 根据ID查询角色
     * 需要ROLE_READ权限
     * 
     * @param id 角色ID
     * @return 角色信息
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_READ')")
    public ResponseEntity<RoleDTO> getRoleById(@PathVariable Long id) {
        logger.debug("Fetching role by ID: {}", id);
        RoleDTO role = roleService.getRoleById(id);
        logger.debug("Role fetched successfully: {}", id);
        return ResponseEntity.ok(role);
    }

    /**
     * 分页查询所有角色
     * 需要ROLE_READ权限
     * 
     * @param pageable 分页参数
     * @return 角色信息分页列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('ROLE_READ')")
    public ResponseEntity<Page<RoleDTO>> getAllRoles(Pageable pageable) {
        logger.debug("Fetching all roles with pagination: {}", pageable);
        Page<RoleDTO> roles = roleService.getAllRoles(pageable);
        logger.debug("All roles fetched successfully, total: {}", roles.getTotalElements());
        return ResponseEntity.ok(roles);
    }

    /**
     * 为角色分配权限
     * 需要ROLE_ASSIGN_PERMISSIONS权限
     * 
     * @param id 角色ID
     * @param permissionIds 权限ID集合
     * @return 更新后的角色信息
     */
    @PostMapping("/{id}/permissions")
    @PreAuthorize("hasAuthority('ROLE_ASSIGN_PERMISSIONS')")
    public ResponseEntity<RoleDTO> assignPermissions(@PathVariable Long id, @RequestBody Set<Long> permissionIds) {
        logger.info("Assigning {} permissions to role: {}", permissionIds.size(), id);
        RoleDTO updatedRole = roleService.assignPermissions(id, permissionIds);
        logger.info("Permissions assigned successfully to role: {}", id);
        return ResponseEntity.ok(updatedRole);
    }
} 